#include <cassert>
#include "widget.h"

#include <lua.hpp>
#include <tolua++.h>

using namespace fltk;

LuaWidget::LuaWidget(lua_State* L_, int x, int y, int w, int h, const char* l) : Widget(x,y,w,h,l),
    key(LUA_NOREF),
    L(L_)
{
}
LuaWidget::~LuaWidget()
{
    if (key != LUA_NOREF)
    {
        luaL_unref(L, LUA_REGISTRYINDEX, key);
        key = LUA_NOREF;
    }
}

int LuaWidget::handle(int id)
{
    if (key == LUA_NOREF)
        return Widget::handle(id);

    // call the 'handle_callback'
    lua_rawgeti(L, LUA_REGISTRYINDEX, key);

    // push the event id arg
    lua_pushinteger(L, id);

    // call
    if (lua_pcall(L, 1, 1, 0) != 0)
    {
        fprintf(stderr, "LuaWidget handle_callback failed to run:\n%s\n", lua_tostring(L, -1));
        return 0;
    }

    // fetch return value (used or not)
    if (!lua_isboolean(L, -1))
    {
        fprintf(stderr, "warning: handle_callback must return boolean, passing event through\n");
        return 0;
    }

    return lua_toboolean(L,-1) != 0;
}

void LuaWidget::handle_callback(int fi)
{
    printf("lua check type is function\n");
    if (!lua_isfunction(L, fi))
    {
        fprintf(stderr, "can only register function as handler_callback");
        return;
    }
    printf("it's a function\n");

    // copy the function at index 'fi'
    lua_pushvalue(L, fi);

    // place it in the registry
    key = luaL_ref(L, LUA_REGISTRYINDEX);
}
